import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:voice_flip_clock/settings_page.dart';
import 'package:voice_flip_clock/widgets/flip_digit.dart';
import 'package:voice_flip_clock/widgets/settings_buttons.dart';
import 'dart:async';
import 'package:flutter_tts/flutter_tts.dart';

import 'hex_color.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  GetStorage box = GetStorage();
  Color _bgColor = Colors.black;
  Color _digitalColor = Colors.grey[300]!;
  Color _digitalBgColor = Colors.black;
  Color _digitalShadowColor = Colors.pink[100]!;
  late Timer _timer;
  late DateTime _currentTime;
  final FlutterTts _flutterTts = FlutterTts();
  String _selectedOption = 'none'; // 默认不播报

  @override
  void initState() {
    super.initState();
    _currentTime = DateTime.now();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _currentTime = DateTime.now();
      });
      _speakCurrentTime(); // 每秒检查并播报
    });
    initData();
    initializeFlutterTts();
  }

  Future<void> initializeFlutterTts() async {
    await _flutterTts.setLanguage('zh-CN');
    await _flutterTts.setSpeechRate(0.5);
    await _flutterTts.setVolume(1.0);
    await _flutterTts.setPitch(1.0);

    _flutterTts.setStartHandler(() {
      print('====================================================================== onStart');
    });

    _flutterTts.setCompletionHandler(() {
      print('====================================================================== onCompleted');
    });

    _flutterTts.setErrorHandler((msg) {
      print('====================================================================== error: $msg');
    });
  }

  void initData() {
    int? bgColor = box.read('bgColor');
    if (bgColor != null) {
      _bgColor = HexColor(bgColor.toRadixString(16));
    } else {
      box.write('bgColor', _bgColor);
    }
    int? digitalColor = box.read('digitalColor');
    if (digitalColor != null) {
      _digitalColor = HexColor(digitalColor.toRadixString(16));
    } else {
      box.write('digitalColor', _digitalColor);
    }
    int? digitalBgColor = box.read('digitalBgColor');
    if (digitalBgColor != null) {
      _digitalBgColor = HexColor(digitalBgColor.toRadixString(16));
    } else {
      box.write('digitalBgColor', _digitalBgColor);
    }
    int? digitalShadowColor = box.read('digitalShadowColor');
    if (digitalShadowColor != null) {
      _digitalShadowColor = HexColor(digitalShadowColor.toRadixString(16));
    } else {
      box.write('digitalShadowColor', _digitalShadowColor);
    }
    setState(() {});
  }

  void _speakCurrentTime() async {
    if (_selectedOption == 'none') return; // 不播报
    await _flutterTts.stop();

    if (_selectedOption == 'second') {
      await _flutterTts.speak('${_currentTime.second}');
    } else if (_selectedOption == 'minute' && _currentTime.second == 0) {
      await _flutterTts.speak('${_currentTime.hour}点${_currentTime.minute}分');
    } else if (_selectedOption == 'hour' && _currentTime.minute == 0 && _currentTime.second == 0) {
      await _flutterTts.speak('${_currentTime.hour}点${_currentTime.minute}分');
    }
  }

  @override
  void dispose() {
    _timer.cancel();
    _flutterTts.stop();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _selectedOption = box.read<String>("selectedOption") ?? 'none'; // 提供默认值 'none'
    return Scaffold(
      backgroundColor: _bgColor,
      body: Stack(
        children: [
          // 时钟显示
          TimeDisplay(currentTime: _currentTime),
          // 设置按钮
          const SettingsButtons(),
        ],
      ),
    );
  }
}

// 将时钟显示部分抽取为单独的widget
class TimeDisplay extends StatelessWidget {
  final DateTime currentTime;

  const TimeDisplay({
    super.key,
    required this.currentTime,
  });

  @override
  Widget build(BuildContext context) {
    final hours = currentTime.hour.toString().padLeft(2, '0');
    final minutes = currentTime.minute.toString().padLeft(2, '0');
    final seconds = currentTime.second.toString().padLeft(2, '0');

    return Stack(
      children: [
        Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 小时
              FlipDigit(value: hours[0]),
              const SizedBox(width: 4),
              FlipDigit(value: hours[1]),
              const SizedBox(width: 8),
              const Text(':',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 50,
                ),
              ),
              const SizedBox(width: 8),
              // 分钟
              FlipDigit(value: minutes[0]),
              const SizedBox(width: 4),
              FlipDigit(value: minutes[1]),
              const SizedBox(width: 8),
              const Text(':',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 50,
                ),
              ),
              const SizedBox(width: 8),
              // 秒钟
              FlipDigit(value: seconds[0]),
              const SizedBox(width: 4),
              FlipDigit(value: seconds[1]),
            ],
          ),
        ),

        // 左侧日期显示（原来是右侧）
        Positioned(
          left: 24,  // 改为 left
          top: 24,
          child: Text(
            '${currentTime.year}年${currentTime.month.toString().padLeft(2, '0')}月${currentTime.day.toString().padLeft(2, '0')}日 ${_getWeekDay(currentTime.weekday)}',
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 24,
            ),
          ),
        ),
      ],
    );
  }

  String _getWeekDay(int weekday) {
    const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    return '星期${weekdays[weekday - 1]}';
  }
}
